// 动态路由
import { getAsyncRoutes } from "@/api/routes";
import router from "@/router";
import Layout from "@/layout/index.vue";
import { routes } from "./index";
import { useRouterStore } from "@/stores/modules/router.ts";
import { setItem, getItem } from "@/utils/common.ts";
const modulesRoutes = import.meta.glob("/src/views/**/*index.{vue,tsx}");

function initRouter() {
  return new Promise((resolve) => {
    getAsyncRoutes().then(({ data }) => {
      const routeList = addAsyncRoutes(filterRoutes(data));
      useRouterStore().saveAsyncRouter(routeList);
      routeList.forEach((e: any) => {
        router.addRoute(e);
      });
      router.addRoute({
        path: "/:pathMatch(.*)*",
        name: "notFound",
        redirect: "/error/404",
      });
      resolve(router.options);
    });
  });
}

//过滤无权限菜单
function filterRoutes(routerList: any) {
  if (!routerList || !routerList.length) return;
  const userRole = getItem("user").roles[0];
  const newData = routerList.filter((v: any) => {
    if (v?.meta?.roles?.includes(userRole)) {
      if (v.children && v.children?.length > 0) {
        v.children = filterRoutes(v.children);
      }
      return v;
    }
  });
  return newData;
}

/** 过滤后端传来的动态路由 重新生成规范路由 */
function addAsyncRoutes(routerList: any) {
  if (!routerList || !routerList.length) return;
  routerList.forEach((v: any) => {
    // 将backstage属性加入meta，标识此路由为后端返回路由
    // v.meta.backstage = true;
    if (v.children && v.children?.length > 0) {
      v.redirect = v.children[0].path;
      if (v.meta.rank) {
        v.component = Layout;
      }
      addAsyncRoutes(v.children);
    } else {
      for (let i in modulesRoutes) {
        if (i.includes(v.path)) {
          v.component = modulesRoutes[i];
        }
      }
    }
  });
  return routerList;
}

export { initRouter, addAsyncRoutes };
